//
//  LoginViewController.m
//  YYPHSpeedJump
//
//  Created by sujiang on 15/12/17.
//  Copyright © 2015年 sujiang. All rights reserved.
//

#import "LoginViewController.h"
#import "LableAndTextField.h"
#import "InvationCode.h"
#import "FIndPasswordViewController.h"

@interface LoginViewController ()<UITextFieldDelegate>
{
    LableAndTextField *phoneNumView;
    LableAndTextField *passwordView;
}
@property (nonatomic, strong) UIButton *loginBtn;
@property (nonatomic, strong) NSMutableString *str;
@property (nonatomic, strong) NSString *placeHolder;
@property (nonatomic, strong) UIButton *QQLoginBtn;
@property (nonatomic, strong) UIButton *WXLoginBtn;
@property (nonatomic, strong) UIButton *SinaLoginBtn;
@property (nonatomic, strong) UIButton *lostPasswordBtn;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kColors(239, 239, 244, 1);
    [self addSubViews];
    
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [self.view endEditing:YES];
}

- (NSMutableString *)str
{
    if (!_str) {
        _str = [NSMutableString string];
    }
    return _str;
}

- (void)addSubViews
{
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigationBg"] forBarMetrics:(UIBarMetricsDefault)];
    self.navigationItem.title = @"登录";
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"fanhui"] style:(UIBarButtonItemStylePlain) target:self action:@selector(actionBack:)];
    self.navigationItem.leftBarButtonItem.tintColor = kColors(255, 255, 255, 1);
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor], NSFontAttributeName:[UIFont systemFontOfSize:20]}];
    
    self.navigationItem.rightBarButtonItem=  [[UIBarButtonItem alloc] initWithTitle:@"注册" style:(UIBarButtonItemStylePlain) target:self action:@selector(actionRightBarBtn:)];
    self.navigationItem.rightBarButtonItem.tintColor = kColors(255, 255, 255, 1);

    
    phoneNumView = [[LableAndTextField alloc] initWithFrame:CGRectMake(0, 7, kScreenWidth, 44) lableText:@"+86" placeHolderText:@"请输入手机号"];
    [self.view addSubview:phoneNumView];
    phoneNumView.textField.keyboardType = UIKeyboardTypePhonePad;
    phoneNumView.textField.returnKeyType = UIReturnKeyDone;
    
    passwordView = [[LableAndTextField alloc] initWithFrame:CGRectMake(0, phoneNumView.bottom + 7, kScreenWidth, 44) lableText:@"密码" placeHolderText:@"请输入密码"];
    [self.view addSubview:passwordView];
    passwordView.textField.delegate = self;
    passwordView.textField.secureTextEntry = YES;
    passwordView.textField.returnKeyType = UIReturnKeyDone;
    
    self.loginBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.loginBtn.frame = CGRectMake(21.5, passwordView.bottom + 12.5, kScreenWidth - 43, 44);
    [self.loginBtn setBackgroundImage:[UIImage imageNamed:@"zydenglu01"] forState:(UIControlStateNormal)];
    [self.view addSubview:self.loginBtn];
    [self.loginBtn addTarget:self action:@selector(actionLogin:) forControlEvents:(UIControlEventTouchUpInside)];
    self.loginBtn.userInteractionEnabled = NO;
    
    self.lostPasswordBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.lostPasswordBtn.frame  = CGRectMake(self.loginBtn.right - 80 * kWidthScale, self.loginBtn.bottom + 12, 80 * kWidthScale, 20);
    [self.view addSubview:self.lostPasswordBtn];
    [self.lostPasswordBtn setTitleColor:kColors(127, 127, 127, 1) forState:(UIControlStateNormal)];
    [self.lostPasswordBtn setTitle:@"忘记密码了?" forState:(UIControlStateNormal)];
    self.lostPasswordBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [self.lostPasswordBtn addTarget:self action:@selector(actionFindPasswordBtn:) forControlEvents:(UIControlEventTouchUpInside)];
    
#pragma mark -----------------  第三方登录 --------------------
     //[self theLineOfThird];
}


- (void)theLineOfThird
{
    UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(22 * kWidthScale, kScreenHeight - 214 * kHeightScale, kScreenWidth - 44 * kWidthScale, 26)];
    [self.view addSubview:aView];
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 12, 116 * kWidthScale, 2)];
    leftView.backgroundColor = kColors(127, 127, 127, 1);
    [aView addSubview:leftView];
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(leftView.right + 5, 0, aView.width - 2 * leftView.width - 10, aView.height)];
    [aView addSubview:lable];
    lable.text = @"第三方登录";
    lable.textColor = kColors(127, 127, 127, 1);
    lable.font = [UIFont systemFontOfSize:14];
    
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(lable.right + 5, 12, 116 * kWidthScale, 2)];
    [aView addSubview:rightView];
    rightView.backgroundColor = kColors(127, 127, 127, 1);
    
    self.QQLoginBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.QQLoginBtn.frame = CGRectMake(27.5 * kWidthScale, aView.bottom + 30 * kHeightScale, 48 * kWidthScale, 52.5 * kHeightScale);
    [self.view addSubview:self.QQLoginBtn];
    [self.QQLoginBtn setBackgroundImage:[UIImage imageNamed:@"qq"] forState:(UIControlStateNormal)];
    [self.QQLoginBtn addTarget:self action:@selector(actionLoginBtn:) forControlEvents:(UIControlEventTouchUpInside)];
    self.QQLoginBtn.tag = 100;
    
    self.WXLoginBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.WXLoginBtn.frame = CGRectMake(self.QQLoginBtn.right + 84 * kWidthScale, self.QQLoginBtn.top, 58.5 * kWidthScale, 54 * kHeightScale);
    [self.view addSubview:self.WXLoginBtn];
    [self.WXLoginBtn setBackgroundImage:[UIImage imageNamed:@"weixin"] forState:(UIControlStateNormal)];
    [self.WXLoginBtn addTarget:self action:@selector(actionLoginBtn:) forControlEvents:(UIControlEventTouchUpInside)];
    self.WXLoginBtn.tag = 101;
    
    self.SinaLoginBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.SinaLoginBtn.frame = CGRectMake(self.WXLoginBtn.right + 70 * kWidthScale, self.WXLoginBtn.top, 60.5 * kWidthScale, 52.5 * kHeightScale);
    [self.view addSubview:self.SinaLoginBtn];
    [self.SinaLoginBtn setBackgroundImage:[UIImage imageNamed:@"weibo"] forState:(UIControlStateNormal)];
    [self.SinaLoginBtn addTarget:self action:@selector(actionLoginBtn:) forControlEvents:(UIControlEventTouchUpInside)];
    self.SinaLoginBtn.tag = 102;
}


#pragma mark -- 按钮的点击事件
- (void)actionLoginBtn:(UIButton *)button
{
    switch (button.tag) {
        case 100:
            // qq
            break;
        case 101:
            // 微信
            break;
        case 102:
            // 新浪微博
            break;
        default:
            break;
    }
    
}

- (void)actionFindPasswordBtn:(UIButton *)button
{
    FIndPasswordViewController *findVC = [[FIndPasswordViewController alloc] init];
    [self.navigationController pushViewController:findVC animated:YES];
}


- (void)actionRightBarBtn:(UIBarButtonItem *)rightBarBtn
{
    InvationCode *invaVC = [[InvationCode alloc] init];
    [self.navigationController pushViewController:invaVC animated:YES];
}

- (void)actionLogin:(UIButton *)button
{
    // 登录
    NSString *url = [NSString stringWithFormat:@"%@%@", kBaseUrl, kLoginUrl];
    NSDictionary *dict = @{@"phone":phoneNumView.textField.text, @"password":passwordView.textField.text};
    [NetworkHandle addToWindow];
    [NetworkHandle registAndLoginByUrl:url dict:dict success:^(NSDictionary *dictionary) {
       // NSLog(@"======%@", dictionary);
        [NetworkHandle removeFromWindow];
        if ([dictionary[@"code"] isEqualToString:@"200"]) {
            
            self.model = dictionary[@"model"];
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"default_login"];
            [[NSUserDefaults standardUserDefaults] setValue:self.model.user_id forKey:@"user_id"];
            [[NSUserDefaults standardUserDefaults] setObject:self.model.nickname forKey:@"userName"];
            [[NSUserDefaults standardUserDefaults] setObject:self.model.birthday forKey:@"birthday"];
            [[NSUserDefaults standardUserDefaults] setObject:self.model.gender forKey:@"selectIndex"];
            [[NSUserDefaults standardUserDefaults] setObject:self.model.head_img_url forKey:@"headerImageUrl"];

            [[NSUserDefaults standardUserDefaults] setObject:self.model.phone forKey:@"phonenumber"];
            
            
            NSURL *url = [[NSURL alloc] initWithString:self.model.head_img_url];
            NSData *data =[[NSData alloc] initWithContentsOfURL:url];
            UIImage *image = [[UIImage alloc] initWithData:data];
           // NSLog(@"%@",image);
            [[NSUserDefaults standardUserDefaults]setObject:UIImagePNGRepresentation(image) forKey:@"headerImage1"];
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"logined"];
            [self.view endEditing:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
                [app setRootVC];
                [self dismissViewControllerAnimated:YES completion:nil];
            });

            
            
        } else {
            [Tools showAlert:@"账号密码不正确,请检查后再试!"];
        }
    
    }];
}


- (void)actionBack:(UIBarButtonItem *)leftBar
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -- 判断登录按钮的颜色

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (toBeString.length >= 6) {
        [self.loginBtn setBackgroundImage:[UIImage imageNamed:@"zydenglu"] forState:(UIControlStateNormal)];
            self.loginBtn.userInteractionEnabled = YES;
    }else {
            [self.loginBtn setBackgroundImage:[UIImage imageNamed:@"zydenglu01"] forState:(UIControlStateNormal)];
            self.loginBtn.userInteractionEnabled = NO;
        }
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    self.placeHolder = textField.placeholder;
    textField.placeholder = nil;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if ([textField.text isEqualToString:@""]) {
        textField.placeholder = self.placeHolder;
    }
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [passwordView.textField resignFirstResponder];
    [phoneNumView.textField resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
